/*
 *   __  __                 _     _       _
 *  |  \/  | ___  ___  __ _| |   (_)_ __ | | __
 *  | |\/| |/ _ \/ __|/ _` | |   | | '_ \| |/ /
 *  | |  | |  __/\__ \ (_| | |___| | | | |   <
 *  |_|  |_|\___||___/\__,_|_____|_|_| |_|_|\_\
 *
 * Copyright (c) 2017-2018, The MesaLink Authors.
 * All rights reserved.
 *
 * This work is licensed under the terms of the BSD 3-Clause License.
 * For a copy, see the LICENSE file.
 *
 */

#[cfg(unix)]
fn generate_la(lib: &str) -> std::io::Result<()> {
    use std::env;
    use std::fs;
    use std::fs::File;
    use std::io::prelude::*;
    use std::path::PathBuf;

    let self_version = env!("CARGO_PKG_VERSION");
    let top_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let profile = env::var("PROFILE").unwrap();
    let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
    let target_dir = match env::var("CARGO_TARGET_SUBDIR") {
        Ok(dir) => format!("{}/target/{}", top_dir, dir),
        Err(_) => format!("{}/target/{}", top_dir, profile),
    };
    let libs_dir = format!("{}/.libs", target_dir);
    let libs_path = PathBuf::from(&libs_dir);
    let la_path = PathBuf::from(format!("{}/{}.la", target_dir, lib));
    let old_lib_path = PathBuf::from(format!("{}/{}.a", target_dir, lib));
    let new_lib_path = PathBuf::from(format!("{}/{}.a", libs_dir, lib));
    if !libs_path.exists() {
        fs::create_dir_all(&libs_path)?;
    }
    if la_path.exists() {
        fs::remove_file(&la_path)?;
    }
    if new_lib_path.exists() {
        fs::remove_file(&new_lib_path)?;
    }
    let mut file = File::create(&la_path)?;
    writeln!(file, "# {}.la - a libtool library file", lib)?;
    writeln!(file, "# Generated by libtool-rust {}", self_version)?;
    writeln!(file, "dlname=''")?;
    writeln!(file, "library_names=''")?;
    writeln!(file, "old_library='{}.a'", lib)?;
    if target_os == "macos" {
        writeln!(
            file,
            "inherited_linker_flags=' -lm -ldl -lresolv -framework Security'"
        )?;
    } else {
        writeln!(file, "inherited_linker_flags=' -pthread -lm -ldl'")?;
    }
    writeln!(file, "installed=no")?;
    writeln!(file, "shouldnotlink=no")?;
    std::os::unix::fs::symlink(&old_lib_path, &new_lib_path)?;
    Ok(())
}

#[cfg(windows)]
fn generate_la(_lib: &str) -> std::io::Result<()> {
    Ok(())
}

fn main() {
    let lib_name = format!("{}{}", "lib", std::env::var("CARGO_PKG_NAME").unwrap(),);
    let _ = generate_la(lib_name.as_str());
}
